import time
import device
import myserial
import pyvisa
import math

#测试前需要配置的参数
fre_band_num = 12 #频段数
fre_pts_num=8  #每个频段的频点数
power_ref=[14.0, 23.0, 33.0, 36.0]  #参考功率值
typename = 'GP14'  #型号
port = 'com5'    #串口端口编号

instrument_address='USB0::0x0957::0x0A0B::MY53420201::0::INSTR'   #示波器地址
#End

power_level_num=len(power_ref)


def create_new_file(base_name="_power_table", extension="txt"):
    counter = 1
    while True:
        # 构建文件名
        filename = f"{typename}{base_name}{counter}.{extension}"
        try:
            # 尝试以写模式打开文件，如果文件不存在则创建
            # 使用x模式可以确保只有文件不存在时才会创建
            with open(filename, 'x'):
                print(f"已创建文件: {filename}")
                return filename
        except FileExistsError:
            # 如果文件已存在，递增计数器并尝试下一个文件名
            counter += 1


if __name__ == '__main__':

    #配置串口
    myserial.serial_port_init(port)

    #配置测量参数
    file_name = create_new_file()

    #链接仪器
    rm = pyvisa.ResourceManager()
    my_instrument = rm.open_resource(instrument_address)

    #发射器初始化：11 P0
    device.init()

    #开启标注
    my_instrument.write(":CALC1:MARK1:STAT ON")

    for i in range(fre_band_num):
        file = open(file_name, 'a')
        file.write('FRE_BAND' + str(i+1) + ':\n')
        print('FRE_BAND' + str(i+1) + ':\n')

        for j in range(fre_pts_num):
            #提高功率挡位
            device.change_pit()
            time.sleep(2)
            # 标注最大值
            my_instrument.write(":CALC1:MARK1:MAX:PEAK")
            #读取峰值频率
            file.write('\t'+str(float(my_instrument.query("CALC:MARK1:X?")) / 10 ** 9) + 'GHz:\n')
            print('峰值频率:', float(my_instrument.query("CALC:MARK1:X?")) / 10 ** 9, 'GHz\n')

            for k in range(power_level_num):
                #标注最大值
                my_instrument.write(":CALC1:MARK1:MAX:PEAK")
                #读取当前峰值功率
                power_now=float(my_instrument.query("CALC:MARK1:Y?"))
                #功率校准(非最大功率挡位）最多校准10次
                if k != power_level_num-1:
                    cnt = 0
                    while not(0 < float(power_now - power_ref[k]) < 1.4 ):
                        cnt += 1
                        power_last = power_now
                        if power_now > power_ref[k]:
                            #微调减小功率
                            device.dec()
                        else:
                            #微调增大功率
                            device.add()
                        # 标注最大值
                        my_instrument.write(":CALC1:MARK1:MAX:PEAK")
                        # 读取当前峰值功率
                        power_now = float(my_instrument.query("CALC:MARK1:Y?"))
                        if cnt >= 30:
                            break
                        if k != 0:
                            if power_now > power_ref[k] and math.fabs(power_now - power_last)<0.25 and cnt >= 10 :
                                break
                        else:
                            if power_now > power_ref[k] and math.fabs(power_now - power_last)<0.25 and cnt >= 20 :
                                break


                #保存功率校准数据
                device.save()
                if not(0<float(power_now - power_ref[k])<1.4):
                    print("下述功率无法调至期望范围")
                file.write('\t\t'+str(power_now) +'dBm\n')
                print('峰值功率:',str(power_now),'dBm\n')
                #提高功率挡位
                device.change_pw()
                #延时
                time.sleep(2)

            # 切换频率
            device.change_pt()
            #print('切换频率')

        # 切换频段
        device.change_band()
        #print('切换频段')
        file.write('\n')
        file.close()

    #关闭串口
    myserial.serial_port_close()
    print("测量完毕")
    